/*
 * Copyright (C) 2013 Ted Kosan
 * 
 * This file is part of MathPiper Exercise.
 * 
 * Foobar is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License as 
 * published by the Free Software Foundation, either version 3 of
 * the License, or (at your option) any later version.
 * 
 * Foobar is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU Lesser General Public License for more details.
 * 
 * You should have received a copy of the GNU Lesser General Public License
 * along with Foobar. If not, see <http://www.gnu.org/licenses/>.
*/

package org.mathpiper.ui.gui.android;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;

import org.mathpiper.interpreters.EvaluationResponse;
import org.mathpiper.ui.gui.android.ExerciseService.LocalBinder;

import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.IBinder;
import android.preference.CheckBoxPreference;
import android.preference.EditTextPreference;
import android.preference.MultiSelectListPreference;
import android.preference.Preference;
import android.preference.PreferenceActivity;
import android.preference.PreferenceManager;
import android.preference.PreferenceScreen;

public class PreferencesActivity extends PreferenceActivity implements ServiceConnection {

    private ExerciseService exerciseService;

    private static final String TAG = "PreferencesActivity";


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        Intent intent = new Intent(this, ExerciseService.class);
        bindService(intent, this, Context.BIND_AUTO_CREATE);


    }


    private PreferenceScreen createPreferenceHierarchy() {
        // Root
        PreferenceScreen root = getPreferenceManager().createPreferenceScreen(this);


        try {
            return initialize(root);
        } catch (Throwable e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        return root;
    }


    private PreferenceScreen initialize(PreferenceScreen root) throws Throwable {

        String exercisePackage = exerciseService.getGlobalString("exercisePackage");

        EvaluationResponse response = exerciseService.evaluate("ConfigurationsGet();");

        String result;

        if (response.isExceptionThrown()) {
            throw response.getException();
        } else {
            result = response.getResult();

            //result = result.replace("\"", "");

            String[] configurations = result.split(";");

            for (String configuration : configurations) {
                String[] values = configuration.split("\\|");

                String name = values[0].trim();

                String type = values[1].trim();

                String configurationDefaultValue = values[2].trim();

                if (type.equals("Integer")) {
                    // Edit text preference
                    EditTextPreference editTextPref = new EditTextPreference(this);
                    editTextPref.setDialogTitle(name);
                    editTextPref.setKey(exercisePackage + "." + name + ":" + type);
                    editTextPref.setTitle(name);
                    //editTextPref.setSummary("test summary");
                    editTextPref.setDefaultValue(configurationDefaultValue);
                    root.addPreference(editTextPref);
                } else if (type.equals("StringMulti")) {

                    String mostRecentValue = PreferenceManager
                            .getDefaultSharedPreferences(this)
                            .getString(exercisePackage + "." + name + ":" + type, configurationDefaultValue);


                    MultiSelectListPreference multiSelectListPref = new MultiSelectListPreference(this);
                    multiSelectListPref.setTitle(name);

                    //multiSelectListPref.setKey(name + ":" + type);

                    ArrayList<String> entriesArrayList = new ArrayList<String>();

                    ArrayList<String> entryValuesArrayList = new ArrayList<String>();

                    String[] operationsString = mostRecentValue.split(":");

                    for (int index = 0; index < operationsString[0].length(); index++) {

                        char operator = operationsString[0].charAt(index);

                        entriesArrayList.add(String.valueOf(operator));

                        entryValuesArrayList.add(String.valueOf(operator));
                    }

                    String[] entries = entriesArrayList.toArray(new String[entriesArrayList.size()]);

                    String[] entryValues = entryValuesArrayList.toArray(new String[entryValuesArrayList.size()]);

                    multiSelectListPref.setEntries(entries);

                    multiSelectListPref.setEntryValues(entryValues);

                    Set<String> set = new HashSet<String>();

                    for (int index = 0; index < operationsString[1].length(); index++) {

                        char operator = operationsString[1].charAt(index);

                        set.add(String.valueOf(operator));
                    }
                    multiSelectListPref.setValues(set);

                    MultiSelectListPreferenceHandler handler = new MultiSelectListPreferenceHandler(exercisePackage + "." + name + ":" + type, operationsString[0], this);

                    multiSelectListPref.setOnPreferenceChangeListener(handler);

                    root.addPreference(multiSelectListPref);
                }
            }

        }//end else.

        CheckBoxPreference speakPreference = new CheckBoxPreference(this);
        speakPreference.setDefaultValue(false);
        speakPreference.setTitle("Speak");
        speakPreference.setKey(exercisePackage + "." + "speak:Boolean");
        root.addPreference(speakPreference);

        CheckBoxPreference listenPreference = new CheckBoxPreference(this);
        listenPreference.setDefaultValue(false);
        listenPreference.setTitle("Listen");
        listenPreference.setKey(exercisePackage + "." + "listen:Boolean");
        root.addPreference(listenPreference);


        EditTextPreference editTextPref = new EditTextPreference(this);
        editTextPref.setDialogTitle("Timer");
        editTextPref.setKey(exercisePackage + "." + "timer:Integer");
        editTextPref.setTitle("timer");
        editTextPref.setDefaultValue("0");
        root.addPreference(editTextPref);

        return root;
    }// end method.


    @Override
    public void onServiceConnected(ComponentName name, IBinder service) {
        LocalBinder binder = (LocalBinder) service;
        exerciseService = binder.getService();

        setPreferenceScreen(createPreferenceHierarchy());

    }


    @Override
    public void onServiceDisconnected(ComponentName name) {
        // TODO Auto-generated method stub

    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        this.unbindService(this);
    }
}